#include "eeprom.h"

#include "stm8l15x_flash.h"

/**
 * 256 字节大小
 * start add:0x1000
 * end add:0x10ff
 */
void EEPROM_Initialize(void)
{
    // 设置编程时间，指定编程时间即可
    FLASH_SetProgrammingTime(FLASH_ProgramTime_Standard);

    // 解锁EEPROM区域（注意type是Data）
    FLASH_Unlock(FLASH_MemType_Data);

    // 等待解锁成功
    while (FLASH_GetFlagStatus(FLASH_FLAG_DUL) == RESET);
}

void EEPROM_Write_Byte(uint16_t Addr,uint8_t Data)
{
    disableInterrupts();
    FLASH_ProgramByte(FLASH_DATA_EEPROM_START_PHYSICAL_ADDRESS + Addr, Data);
    FLASH_WaitForLastOperation(FLASH_MemType_Data);
    enableInterrupts();
}

//注意写的时候一定要写入4字节的整数倍
void EEPROM_Write_Word(uint16_t Addr,uint32_t Data)
{
    disableInterrupts();
    FLASH_Unlock(FLASH_MemType_Data);
    FLASH_ProgramWord(FLASH_DATA_EEPROM_START_PHYSICAL_ADDRESS + Addr, Data);
    FLASH_WaitForLastOperation(FLASH_MemType_Data);//等待操作完成
    FLASH_Lock(FLASH_MemType_Data);
    enableInterrupts();
}

uint8_t EEPROM_Read_Byte(uint16_t Addr)
{
    uint8_t res;
    res = FLASH_ReadByte(FLASH_DATA_EEPROM_START_PHYSICAL_ADDRESS + Addr);
    FLASH_WaitForLastOperation(FLASH_MemType_Data);//等待操作完成
    return res;
}
